//
//  UserInfoService.m
//  HZHome
//
//  Created by SunShine on 13-10-14.
//  Copyright (c) 2013年 xzysun. All rights reserved.
//

#import "UserInfoService.h"
#import "StreetInfoService.h"

@interface UserInfoService ()
@property (strong, nonatomic) NSString *errMsg;
@end
@implementation UserInfoService
static UserInfoService *singleton;

+(UserInfoService *)getUserInfoService
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        singleton = [[UserInfoService alloc]init];
    });
    return singleton;
}

-(void)customiezStreetWithStreetId:(NSString *)streetId
{
    self.errMsg = @"定制街道失败.";
    NSString *currentUserName = self.currentLoginUserName;
    if (currentUserName && currentUserName.length>0) {
        NSLog(@"userCustomInfo id = %@",self.userCustomInfo.Id);
        //用户已登录，进行定制
        NSString *Id = self.userCustomInfo.Id;
//        NSString *Id = @"1";//用户表主键
//        NSString *userId = @"1";//用户ID有错误
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setValue:streetId forKey:@"userStreetId"];
        [params setValue:Id forKey:@"id"];
//        [params setValue:userId forKey:@"userId"];
//        [params setValue:currentUserName forKey:@"userName"];
        [self doHttpPost:STREET_CUSTOMIZE_URL headers:nil path:@"" parameters:params];
    } else {
        //没有登录，直接返回进行本地保存
        if(self.delegate && [self.delegate respondsToSelector:@selector(loadUserInfoFinished:)]){
            [self.delegate loadUserInfoFinished:nil];
        }
    }
}

-(void)checkUserLoginWithName:(NSString *)userName andPassword:(NSString *)password
{
    self.errMsg = @"登录失败,请检查您的用户名密码.";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:userName forKey:@"userName"];
    [params setValue:password forKey:@"password"];
    [self doHttpPost:USER_LOGIN_URL headers:nil path:@"" parameters:params];
    self.lastLoginPassword = md5HexDigest(password);
}
-(void)checkUserLoginWithImdeiCode:(NSString *)imeiCode
{
    self.errMsg = @"登录失败,请检查您的用户名密码.";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:imeiCode forKey:@"imeiCode"];
    [self doHttpPost:USER_LOGIN_WITH_ID_URL headers:nil path:@"" parameters:params];
}


//个人中心修改
-(void)modifyUserInfoWithMobile:(NSString *)mobile Address:(NSString *)address StreetId:(NSInteger)streetId Permanent:(BOOL)permanent WorkHere:(BOOL)workHere
{
    self.errMsg = @"保存用户信息失败.";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:_userInfo.userName forKey:@"userName"];
    [params setValue:_userInfo.nickName forKey:@"nickName"];
    [params setValue:_userInfo.identity forKey:@"identity"];
    [params setValue:mobile forKey:@"mobile"];
    [params setValue:address forKey:@"address"];
    [params setValue:[NSString stringWithFormat:@"%d",streetId] forKey:@"streetId"];
    [params setValue:permanent?@"1":@"0" forKey:@"permanent"];//常住人口
    [params setValue:workHere?@"1":@"0" forKey:@"workHere"];//在此工作
    [params setValue:@"0" forKey:@"partyMember"];//党员
    [params setValue:@"0" forKey:@"volunteers"];//志愿者
    [params setValue:@"0" forKey:@"member"];//团员
    [params setValue:_userInfo.Id forKey:@"id"];
     [params setValue:@"1" forKey:@"isStart"];
    [self doHttpPost:USER_INFO_MODIFY_URL headers:nil path:@"" parameters:params];
}

-(void)modifyUserPassword:(NSString *)password
{
    self.errMsg = @"保存密码失败.";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:_userInfo.Id forKey:@"id"];
    [params setValue:password forKey:@"password"];
    [params setValue:_userInfo.mobile forKey:@"mobile"];
    [params setValue:getDeviceIdentifier() forKey:@"imeiCode"];
    [self doHttpPost:USER_MODIFY_PASSWORD_URL headers:nil path:@"" parameters:params];
}
//检查手机号是否被绑定
-(void)checkUsrMobile:(NSString *)mobile
{
    self.errMsg = @"手机号没有绑定该设备.";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:_userInfo.Id forKey:@"id"];
    [params setValue:mobile forKey:@"mobile"];
    [params setValue:getDeviceIdentifier() forKey:@"imeiCode"];
    [self doHttpPost:USER_CHEC_KMOBILE_URL headers:nil path:@"" parameters:params];
}

-(void)userFeedbackWithContent:(NSString *)content Practicality:(NSInteger)practicality EaseUse:(NSInteger)easeUse
{
    self.errMsg = @"提交反馈数据失败.";
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if (_userInfo) {
        [params setValue:_userInfo.Id forKey:@"FKUser"];
    } else {
        [params setValue:@"" forKey:@"FKUser"];
    }
    [params setValue:content forKey:@"content"];
    if (practicality == 0) {
        [params setValue:@"1" forKey:@"practicality"];
    } else {
        [params setValue:@"0" forKey:@"practicality"];
    }
    if (easeUse == 0) {
        [params setValue:@"1" forKey:@"easeUse"];
    } else {
        [params setValue:@"0" forKey:@"easeUse"];
    }
    if ([UserInfoService getUserInfoService].currentLoginUserName) {
        [params setValue:[UserInfoService getUserInfoService].userInfo.mobile forKey:@"phone"];
    }
    [params setValue:getDeviceIdentifier() forKey:@"imeiCode"];//要加入的唯一标示
    [self doHttpPost:USER_FEEDBACK_URL headers:nil path:@"" parameters:params];
}
//- (void)doPostServerTimer:(NSTimer *)mTimer
//{
//     DoBackGroundMethod();
//}
//保存用户信息
-(void)loginSuccessHandler:(id)json
{
    NSDictionary *infoCustomDic = [json objectForKey:@"infoCustom"];
    NSDictionary *userDic = [json objectForKey:@"user"];
    self.userCustomInfo = getObjectFromDic([UserCustomInfo class], infoCustomDic);
    self.userInfo = getObjectFromDic([UserInfo class], userDic);
    [UserInfoService getUserInfoService].lastLoginPassword=self.userInfo.password;
    self.userInfo.isStart=@"1";//判断是否已经登录-/**0代表未登录，1代表已登录。2，代表已登录注消**/
    isStart=1;//判断是否已经登录-/**0代表未登录，1代表已登录。2，代表已登录注消**/
    [DataStoreService saveToKeychain:AUTO_LOGIN_USER_PASSWORD data:self.userInfo.password];
    [DataStoreService saveToKeychain:LOGIN_USER_ID data:self.userCustomInfo.userId];
    [DataStoreService saveToKeychain:LOGIN_USER_NAME data:self.userCustomInfo.userName];

    self.currentLoginUserName = _userInfo.userName;
    if (_userCustomInfo&&!isBlankString(_userCustomInfo.userStreetId)) {
        [StreetInfoService getService].selectedStreetId = _userCustomInfo.userStreetId;
    }
    
    //保存到全局变量
//    UserInfo *globalUserInfo = [UserInfoService getUserInfoService].userInfo;
//    globalUserInfo.streetId =self.userInfo.streetId;
//    globalUserInfo.permanent = self.userInfo.permanent;
//    globalUserInfo.workHere = self.userInfo.workHere;
//    globalUserInfo.address = self.userInfo.address;
//    globalUserInfo.mobile = self.userInfo.mobile;
 
//    // 定义一个NSTimer---每隔15分钟请求一次
//    self.postTimer = [NSTimer scheduledTimerWithTimeInterval:900.0
//                                                          target:self
//                                                        selector:@selector(doPostServerTimer:)  userInfo:nil
//                                                         repeats:YES];
}
-(void)logout
{
    self.currentLoginUserName = nil;
    self.userCustomInfo = nil;
    self.userInfo = nil;
    [[NSNotificationCenter defaultCenter] postNotificationName:LOGOUT_NOTIFICATION_NAME object:self];
    //清理自动登录
    [DataStoreService deleteFromKeychain:AUTO_LOGIN_FLAG];
    [DataStoreService deleteFromKeychain:AUTO_LOGIN_USER_NAME];
    [DataStoreService deleteFromKeychain:AUTO_LOGIN_USER_PASSWORD];
}

-(void)doHttpPost:(NSString *)posturl headers:(NSDictionary*)headersOrNil path:(NSString*)path parameters:(NSDictionary *)params
{
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:posturl customHeaderFields:headersOrNil];
    MKNetworkOperation *op = [currentEngine operationWithPath:path params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        
        NSDictionary *json = [operation responseJSON];
        if (json) {
            BOOL isSuccess = ((NSNumber*)[json objectForKey:@"isSuccess"]).boolValue;
            //执行回调
            if (isSuccess) {
                if (self.delegate && [self.delegate respondsToSelector:@selector(loadUserInfoFinished:)]) {
                    [self.delegate loadUserInfoFinished:json];
                }
               
            } else {
                if (self.delegate && [self.delegate respondsToSelector:@selector(loadUserInfoFaild:)]) {
                    [self.delegate loadUserInfoFaild:self.errMsg];
                }
            }

        }
        NSString *jsonString=[operation responseString];
        if ([jsonString compare:@"true"]==NSOrderedSame) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"提交成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            [self.delegate loadUserInfoFinished:jsonString];
        }
        
    }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
        NSLog(@"MKNetwork request error : %@", [err localizedDescription]);
        if (self.delegate && [self.delegate respondsToSelector:@selector(loadUserInfoFaild:)]) {
            [self.delegate loadUserInfoFaild:@"服务器网络异常"];
        }
    }];
    [currentEngine enqueueOperation:op];
}

//注册用户
-(void)addUserWithName:(NSString *)name Password:(NSString *)password Phone:(NSString *)phone Address:(NSString *)address StreetId:(NSInteger)streetId LiveHere:(BOOL)liveHere WorkHere:(BOOL)workHere
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:name forKey:@"userName"];
    [params setValue:password forKey:@"password"];
    [params setValue:@"" forKey:@"nickName"];
    [params setValue:@"" forKey:@"identity"];
    [params setValue:phone forKey:@"mobile"];
    [params setValue:address forKey:@"address"];
    [params setValue:[NSNumber numberWithInt:streetId] forKey:@"streetId"];
    [params setValue:(liveHere?@"1":@"0") forKey:@"permanent"];
    [params setValue:(workHere?@"1":@"0") forKey:@"workHere"];
    [params setValue:@"0" forKey:@"partyMember"];
    [params setValue:@"0" forKey:@"volunteers"];
    [params setValue:@"0" forKey:@"member"];
    [params setValue:getDeviceIdentifier() forKey:@"imeiCode"];
    [params setValue:@"2" forKey:@"userType"];
    [params setValue:@"1" forKey:@"isStart"];
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:USER_ADD_URL customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        NSLog(@"[注册响应数据]-->>%@", [completedOperation responseString]);
        NSDictionary *json = [completedOperation responseJSON];
        BOOL isSuccess = ((NSNumber*)[json objectForKey:@"isSuccess"]).boolValue;
        
        if (isSuccess) {
            //执行登录
//            [self autoLogin];
            //调用登录
            [[UserInfoService getUserInfoService] checkUserLoginWithName:name andPassword:password];
        } else {
            //错误提示
            NSString *message = [json objectForKey:@"message"];
            if (self.delegate && [self.delegate respondsToSelector:@selector(loadUserInfoFaild:)]) {
                [self.delegate loadUserInfoFaild:message];
            }
        }
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(loadUserInfoFaild:)]) {
            [self.delegate loadUserInfoFaild: @"注册用户失败"];
        }
    }];
    [currentEngine enqueueOperation:op];
}
//自动登录
-(void)autoLogin
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    NSString *userName = [DataStoreService loadFromKeychain:AUTO_LOGIN_USER_NAME];
//    NSString *userPass = [DataStoreService loadFromKeychain:AUTO_LOGIN_USER_PASSWORD];
//    [params setValue:userName forKey:@"userName"];
//    [params setValue:userPass forKey:@"password"];
    NSString *imeiCode = getDeviceIdentifier();
    //imeiCode=@"000000000000000s";
    [params setValue:imeiCode forKey:@"imeiCode"];
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:USER_LOGIN_WITH_ID_URL customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        
        NSDictionary *json = [completedOperation responseJSON];
        BOOL isSuccess = ((NSNumber*)[json objectForKey:@"isSuccess"]).boolValue;
        if (isSuccess) {
            //[self loginSuccessHandler:json];
            //回调目标类的loadUserInfoFinished
            if (self.delegate && [self.delegate respondsToSelector:@selector(loadUserInfoFinished:)]) {
                [self.delegate loadUserInfoFinished:json];
            }
        } else {
            if (self.delegate && [self.delegate respondsToSelector:@selector(loadUserInfoFaild:)]) {
                [self.delegate loadUserInfoFaild:@"自动登录失败"];
            }
        }
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(loadUserInfoFaild:)]) {
            [self.delegate loadUserInfoFaild:@"自动登录失败"];
        }
    }];
    [currentEngine enqueueOperation:op];
}

//查询手机验证码
-(void)getPhoneCheckNumber:(NSString *)mobile Success:(void (^)(NSDictionary *data))success Failure:(void (^)(NSString *msg))failure{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:mobile forKey:@"mobile"];
    
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName: GET_VALI_NUM customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:nil params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        NSLog(@"[手机验证响应数据]-->>%@", [operation responseString]);
        NSDictionary *json = [operation responseJSON];
        success(json);
    }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
        NSLog(@"MKNetwork request error : %@", [err localizedDescription]);
        //执行回调
        failure(@"请求失败.");
    }];
    [currentEngine enqueueOperation:op];
}
//验证手机号码和验证码是否正确
-(void)valiNum:(NSString *)mobile checkNumber:(NSString *)num Success:(void (^)(NSDictionary *data))success Failure:(void (^)(NSString *msg))failure{

        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setValue:mobile forKey:@"mobile"];
        [params setValue:num forKey:@"valiNum"];
        MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName: CHECK_VALI_NUM customHeaderFields:nil];
        MKNetworkOperation *op = [currentEngine operationWithPath:nil params:params httpMethod:@"POST"];
        [op addCompletionHandler:^(MKNetworkOperation *operation) {
            NSDictionary *json = [operation responseJSON];
            success(json);
        }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
            NSLog(@"MKNetwork request error : %@", [err localizedDescription]);
            //执行回调
            failure(@"请求失败.");
        }];
        [currentEngine enqueueOperation:op];
}

//注册用户2 有回调
-(void)addUser:(NSString *)name Password:(NSString *)password Phone:(NSString *)phone Address:(NSString *)address StreetId:(NSInteger)streetId LiveHere:(BOOL)liveHere WorkHere:(BOOL)workHere Success:(void (^)(NSDictionary *data))success Failure:(void (^)(NSString *msg))failure{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:name forKey:@"userName"];
    [params setValue:password forKey:@"password"];
    [params setValue:@"" forKey:@"nickName"];
    [params setValue:@"" forKey:@"identity"];
    [params setValue:phone forKey:@"mobile"];
    [params setValue:address forKey:@"address"];
    [params setValue:[NSNumber numberWithInt:streetId] forKey:@"streetId"];
    [params setValue:(liveHere?@"1":@"0") forKey:@"permanent"];
    [params setValue:(workHere?@"1":@"0") forKey:@"workHere"];
    [params setValue:@"0" forKey:@"partyMember"];
    [params setValue:@"0" forKey:@"volunteers"];
    [params setValue:@"0" forKey:@"member"];
    [params setValue:getDeviceIdentifier() forKey:@"imeiCode"];
    [params setValue:@"2" forKey:@"userType"];
    [params setValue:@"1" forKey:@"isStart"];
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName: USER_ADD_URL customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:nil params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *operation) {
        NSDictionary *json = [operation responseJSON];
        success(json);
    }errorHandler:^(MKNetworkOperation *errorOp, NSError* err) {
        //执行回调
        failure(@"请求失败.");
    }];
    [currentEngine enqueueOperation:op];

}
@end
